package com.mud.ultimate;

import java.util.Date;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.NativeActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mud.ultimate.data.GameRecord;
import com.mud.ultimate.data.GameRecordDAO;
import com.mud.ultimate.dialogs.HelpDialog;
import com.mud.ultimate.dialogs.NameChangeDialog;
import com.mud.ultimate.dialogs.UploadHighScoreDialog;

public class GameLauncherActivity extends Activity {
	
	
	private static final int LEVEL_STEP = 6000;
	public static int CHANGE_NAME_RESULT = 10;
	public static int UPLOAD_HIGH_SCORE_RESULT = 11;
	
	private GameRecordDAO DAOservice;
	
	private int[] pictureNames;

	private TextView currentScoreTW;
	private TextView bestScoreTW;
	private TextView avgScoreTW;
	private TextView minScoreTW;
	private TextView bestTodayScoreTW;
	private TextView sumTodayScoreTW;
	private TextView numOfGamesTW;
	private ProgressBar xpBarPB;
	private TextView xpTextTV;
	private ImageView rankIW;

	private TextView levelTV;

	private TextView playerNameTV;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game_launcher);
		
		pictureNames=new int[]{R.drawable.rank_bronze_small,R.drawable.rank_silver_small,R.drawable.rank_gold_small,
							   R.drawable.rank_platinum_small,R.drawable.rank_diamond_small,R.drawable.rank_master_small};
		
		playerNameTV = (TextView) findViewById(R.id.playerNameTV);
		currentScoreTW = (TextView) findViewById(R.id.currentScoreTW);
		bestScoreTW = (TextView) findViewById(R.id.bestScoreTW);
		avgScoreTW = (TextView) findViewById(R.id.avgScoreTW);
		minScoreTW = (TextView) findViewById(R.id.minScoreTW);
		bestTodayScoreTW = (TextView) findViewById(R.id.bestTodayScoreTW);
		sumTodayScoreTW = (TextView) findViewById(R.id.sumTodayScoreTW);
		numOfGamesTW = (TextView) findViewById(R.id.numOfGamesTW);
		xpBarPB = (ProgressBar) findViewById(R.id.xpBarPB);
		xpTextTV = (TextView) findViewById(R.id.xpTextTV);
		levelTV = (TextView) findViewById(R.id.levelTV);
		rankIW = (ImageView) findViewById(R.id.rankIW);
		
		
		final Button launch = (Button)findViewById(R.id.playB);
		launch.setOnClickListener(new OnClickListener() {

			
			@Override
			public void onClick(View v) {
				showButtonAnim(launch);
				
				Intent startGameIntent = new Intent(getApplicationContext(),NativeActivity.class);
				startGameIntent.putExtra("gameMode", 0);
				
				startActivityForResult(startGameIntent,99);
				
			}
		});
		
		final Button changeName = (Button)findViewById(R.id.changePlayerB);
		changeName.setOnClickListener(new OnClickListener() {

			
			@Override
			public void onClick(View v) {
				showButtonAnim(changeName);
				
				Intent changeNameIntent = new Intent(getApplicationContext(),NameChangeDialog.class);
			
				
				startActivityForResult(changeNameIntent,CHANGE_NAME_RESULT);
				
			}
		});
		
		final Button highScores = (Button)findViewById(R.id.highScoreB);
		highScores.setOnClickListener(new OnClickListener() {

			
			@Override
			public void onClick(View v) {
				showButtonAnim(highScores);
				Intent highScoresIntent = new Intent(getApplicationContext(),HighScoresActivity.class);
			
				
				startActivity(highScoresIntent);
				
			}
		});
		
		
		final Button helpB = (Button)findViewById(R.id.helpB);
		helpB.setOnClickListener(new OnClickListener() {

			
			@Override
			public void onClick(View v) {
				showButtonAnim(helpB);
				Intent HelpDialogIntent = new Intent(getApplicationContext(),HelpDialog.class);
			
				
				startActivity(HelpDialogIntent);
				
			}
		});
		
		DAOservice = new GameRecordDAO(this);
		DAOservice.open();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.game_launcher, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if(requestCode==CHANGE_NAME_RESULT && resultCode==RESULT_OK)
		{
			SharedPreferences sharedPref = getSharedPreferences("GAME",Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = sharedPref.edit();
			
			String newUserName=data.getExtras().getString(GameHandler.USERNAME_KEY);
			editor.putString(GameHandler.USERNAME_KEY,newUserName);
			
			playerNameTV.setText(newUserName);
			
			editor.putInt(GameHandler.BEST_SCORE_KEY,DAOservice.getbestScore(newUserName));
			editor.putInt(GameHandler.GAME_COUNT_KEY,DAOservice.getGameCount(newUserName));
			editor.putInt(GameHandler.WORST_SCORE_KEY,DAOservice.getworstScore(newUserName));
			editor.putInt(GameHandler.AVG_SCORE_KEY,DAOservice.getavgScore(newUserName));
			editor.putInt(GameHandler.SUM_SCORE_KEY,DAOservice.getsumScore(newUserName));
			editor.putInt(GameHandler.SCORE_KEY,DAOservice.getlastScore(newUserName));
			editor.putInt(GameHandler.BEST_SCORE_TODAY_KEY,DAOservice.getbestScoreToday(newUserName));
			editor.putInt(GameHandler.SUM_SCORE_TODAY_KEY,DAOservice.getsumScoreToday(newUserName));
			
			
			editor.commit();
		}
		
		if(requestCode==UPLOAD_HIGH_SCORE_RESULT && resultCode==RESULT_OK)
		{
			Toast uploadOKToast = Toast.makeText(getApplicationContext(),"High Score uploaded!",Toast.LENGTH_SHORT);
			uploadOKToast.show();
		}
		else if(requestCode==UPLOAD_HIGH_SCORE_RESULT && resultCode==UploadHighScoreDialog.UPLOAD_SCORE_ERROR)
		{
			Toast uploadOKToast = Toast.makeText(getApplicationContext(),"Error during upload!",Toast.LENGTH_SHORT);
			uploadOKToast.show();
			
		}
		
		
		
		
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onResume() {
		GameHandler.context = getApplicationContext();
		
		
		SharedPreferences sharedPref = getSharedPreferences("GAME",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPref.edit();
		String username  = sharedPref.getString(GameHandler.USERNAME_KEY,"John Shepard");
		int score  = sharedPref.getInt(GameHandler.SCORE_KEY,0);
		int bestScore =sharedPref.getInt(GameHandler.BEST_SCORE_KEY, 0);
		int avgScore =sharedPref.getInt(GameHandler.AVG_SCORE_KEY, 0);
		int worstScore =sharedPref.getInt(GameHandler.WORST_SCORE_KEY, 0);
		int sumScore =sharedPref.getInt(GameHandler.SUM_SCORE_KEY, 0);
		int bestScoreToday =sharedPref.getInt(GameHandler.BEST_SCORE_TODAY_KEY, 0);
		int sumScoreToday =sharedPref.getInt(GameHandler.SUM_SCORE_TODAY_KEY, 0);
		int gameCount =sharedPref.getInt(GameHandler.GAME_COUNT_KEY, 0);
		long gameTimestamp =sharedPref.getLong(GameHandler.GAME_TIMESTAMP_KEY, 0);
		boolean newHighScore =sharedPref.getBoolean(GameHandler.NEW_HIGH_SCORE_KEY, false);
		boolean newGameScore =sharedPref.getBoolean(GameHandler.NEW_GAME_SCORE_KEY, false);
		Date lastPlayedDate= new Date(gameTimestamp);
		Date now = new Date();

		playerNameTV.setText(username);
		currentScoreTW.setText(String.valueOf(score));
		bestScoreTW.setText(String.valueOf(bestScore));
		avgScoreTW.setText(String.valueOf(avgScore));
		minScoreTW.setText(String.valueOf(worstScore));
		numOfGamesTW.setText(String.valueOf(gameCount));
		
		
		
		if(lastPlayedDate.getDate()==now.getDate())
		{
			bestTodayScoreTW.setText(String.valueOf(bestScoreToday));
			sumTodayScoreTW.setText(String.valueOf(sumScoreToday));
		}
		else
		{
			bestTodayScoreTW.setText(String.valueOf(0));
			sumTodayScoreTW.setText(String.valueOf(0));
			editor.putInt(GameHandler.BEST_SCORE_TODAY_KEY, 0);
			editor.putInt(GameHandler.SUM_SCORE_TODAY_KEY, 0);
		}
		
		
		for(int i=0;i<pictureNames.length;i++ )
		{
			int nextScoreLevel=(int) (LEVEL_STEP*Math.pow(2, i));
			if(nextScoreLevel>sumScore)
			{
				int lastScoreLevel = (int) (i==0? 0: LEVEL_STEP*Math.pow(2, i-1));
				int scoreInterval = nextScoreLevel-lastScoreLevel;
				float complete =(float) (sumScore-lastScoreLevel)/scoreInterval;
				//xpBarPB.setIndeterminate(false);
				xpBarPB.setProgress((int) (complete*100));
				rankIW.setImageResource(pictureNames[i]);
				xpTextTV.setText(String.valueOf(sumScore)+"/"+String.valueOf(nextScoreLevel));
				levelTV.setText(String.valueOf(i+1));
				break;
			}
			
		}
		if(newGameScore)
		{
			
			editor.putBoolean(GameHandler.NEW_GAME_SCORE_KEY, false);
			DAOservice.createGameRecord(new GameRecord(username, score, now));
		}
		
		
		if(newHighScore)
		{
			Intent highScoreIntent = new Intent(getApplicationContext(),UploadHighScoreDialog.class);
			highScoreIntent.putExtra(GameHandler.USERNAME_KEY,username);
			highScoreIntent.putExtra(GameHandler.SCORE_KEY,score);
			startActivityForResult(highScoreIntent,UPLOAD_HIGH_SCORE_RESULT);

			
			editor.putBoolean(GameHandler.NEW_HIGH_SCORE_KEY, false);
			
		}
		
		editor.commit();
		
		Log.e("JNITEST", "onResume");
		super.onResume();
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
		
		DAOservice.close();
	}
	
	private void showButtonAnim(Button targetB)
	{
		
		Animation showAnim = AnimationUtils.loadAnimation(this,R.anim.pushanim);
		targetB.startAnimation(showAnim);
	}
	
	
	
	
	
	

}
